import actionTypes from './constants';
import {loginRequest} from '../../services';


//同步
//开始登录
const startLogin = () => {
    return {
        type: actionTypes.START_LOGIN
    }
}
//登录成功
const loginSuccess = (adminInfo) => {
    // console.log(adminInfo);
    // console.log("三号点");
    return {
        type: actionTypes.LOAGIN_SUCCESS,
        payLoad: {
            ...adminInfo,
            isLoading:false,
            isLogin:true
        }
    }
}
//登录失败处理
const loginFailed = () => {
    //清除本地记录
    window.localStorage.removeItem('authToken');
    window.sessionStorage.removeItem('authToken');
    window.localStorage.removeItem('adminInfo');
    window.sessionStorage.removeItem('adminInfo');
    return {
        type: actionTypes.LOGIN_FAILED
    }
}


//登录
export const login= (userInfo) => {
    // console.log(userInfo);
    const adminInfoA = {admin_name:userInfo.admin_name, admin_password:userInfo.admin_password};
    // console.log(adminInfoA);
    return dispatch => {
        dispatch(startLogin);
        //网络请求用的是变化后的userInfo
        loginRequest(adminInfoA)
        .then(res => {
            // console.log(res);
            //返回的状态码为200的时候表示登录成功
            if(res.code === 200){
                //在这里需要做本地化存储，存储authToken和adminInfo
                // const {authToken,...userInfo} = res.data.data;
                const authToken = res.data.authToken;
                const adminInfoB = res.data.adminInfo;
                if(userInfo.remember === true){
                    window.localStorage.setItem('authToken', authToken);
                    window.localStorage.setItem('adminInfo', JSON.stringify(adminInfoB));
                    
                }else {
                    window.sessionStorage.setItem('authToken', authToken);
                    window.sessionStorage.setItem('adminInfo', JSON.stringify(adminInfoB));
                }
                dispatch(loginSuccess({
                    ...res.data.adminInfo
                }))
            }else {
                dispatch(loginFailed());
            }
        })
        
    }
}

//登录失败
// export const logout = () => {
//     //实际的项目中需要告诉服务端用户已经退出
//     return dispatch => {
//         dispatch(loginFailed);
//     }
// }

//退出登录测试
export const logout = () => {
    //实际的项目中需要告诉服务端用户已经退出
    // console.log('正在执行退出');
    window.localStorage.removeItem('authToken');
    window.sessionStorage.removeItem('authToken');
    window.localStorage.removeItem('userInfo');
    window.sessionStorage.removeItem('userInfo');
    return {
        type: actionTypes.LOGOUT
    }
}


//上传头像
export const changeAvatar = (avatarUrl) => {
    // console.log(avatarUrl);
    return {
        type: actionTypes.CHANGEAVATAR,
        payLoad: {
            avatarUrl
        }
    }
}